package com.michaelbulava.TFS.vcs.internal;

import com.intellij.openapi.vcs.CheckinProjectPanel;
import com.intellij.openapi.vcs.changes.CommitExecutor;
import com.intellij.openapi.vcs.checkin.CheckinHandler;
import com.intellij.openapi.vcs.checkin.VcsCheckinHandlerFactory;
import com.intellij.util.PairConsumer;
import com.intellij.vcsUtil.VcsUtil;
import com.michaelbulava.TFS.Messages;
import com.michaelbulava.TFS.vcs.TFSVcs;
import com.michaelbulava.TFS.vcs.exceptions.NotConnectedToTFS;
import org.jetbrains.annotations.NotNull;

import java.io.File;

/**
 * Created by MichaelA on 8/19/2015.
 */
public class TFSCheckinHandlerFactory extends VcsCheckinHandlerFactory {

    public TFSCheckinHandlerFactory(){
        super(TFSVcs.getKey());
    }

    @NotNull
    @Override
    protected CheckinHandler createVcsHandler(final CheckinProjectPanel checkinProjectPanel) {
        CheckinHandler handler = new CheckinHandler() {
            @Override
            public ReturnResult beforeCheckin(CommitExecutor executor, PairConsumer<Object, Object> additionalDataConsumer) {
                if (executor != null)
                    return ReturnResult.COMMIT;
                if (!checkinProjectPanel.vcsIsAffected(TFSVcs.VCS_NAME))
                    return ReturnResult.COMMIT;
                boolean reallyAffected = false;
                try {
                    for (File file : checkinProjectPanel.getFiles()) {
                        TFSVcs.getInstance(checkinProjectPanel.getProject()).getWorkspaceForFile(VcsUtil.getFilePath(file));
                        if (!TFSVcs.isUnderTFS(VcsUtil.getFilePath(file), checkinProjectPanel.getProject()) ||
                                TFSVcs.getInstance(checkinProjectPanel.getProject()).isIgnoredFile(VcsUtil.getFilePath(file)))
                            continue;
                        reallyAffected = true;
                        break;
                    }
                } catch (NotConnectedToTFS notConnectedToTFS) {
                    Messages.showErrorDialog(checkinProjectPanel.getProject(),
                            Messages.getString("TFSCheckinHandlerFactory.OfflineModuleErrorText"),
                            Messages.getString("TFSCheckinHandlerFactory.OfflineModuleErrorTitle"));
                    return ReturnResult.CANCEL;
                }
                if (!reallyAffected)
                    return ReturnResult.COMMIT;

                //TODO perform extra validations here, such as policy checks
                return ReturnResult.COMMIT;
            }
        };

        return handler;
    }


}
